package com.traffic.visim.socket;

import com.traffic.visim.kafkamq.register.KafkaProducer;
import com.traffic.visim.onvif.mapper.IOnvifEventMapper;
import com.traffic.visim.service.OnvifService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class DetectorServerSocket {

    @Value("${onvif.socket-port}")
    private Integer port;

    @Autowired
    private KafkaProducer kafkaProducer;

    @Autowired
    IOnvifEventMapper onvifEventMapper;

    @Autowired
    OnvifService onvifService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    public static ServerSocket testSocket = null;

    private static final ThreadPoolExecutor testSocketThreadPool = new ThreadPoolExecutor(15, 15,
            10L, TimeUnit.SECONDS, new LinkedBlockingQueue<>());

    @PostConstruct
    public void start() {
        new Thread(() -> {
            try {
                testSocket = new ServerSocket(port);
                log.info("socket服务端开启");
                while (true){
                    Socket socket = testSocket.accept();
                    testSocketThreadPool.execute(new TestSocketService(socket,kafkaProducer,onvifEventMapper,stringRedisTemplate,onvifService));
                }
            } catch (IOException e) {
                log.info("socket服务启动异常");
                e.printStackTrace();
            }
        }, "testSocket").start();
    }

}
